const {src,dest, watch,series,parallel} = require('gulp');

//服务器插件
const connect = require('gulp-connect');
//代理插件
const {createProxyMiddleware} = require("http-proxy-middleware");
//合并插件
const concat = require('gulp-concat');
// 压缩插件
const uglify = require('gulp-uglify');
// 改名插件
const rename = require('gulp-rename');
//ES6转ES5插件
const babel = require("gulp-babel");
//sass转css插件
const sass = require('gulp-sass') ;






function copyFn(next){
    src(['development/index.html']).pipe(dest('dist'));
    next();
}
exports.copy = copyFn;

// 自动转存：如果开发环境中的文件发生变化，自动转存到运行环境
function watchFn(next){
    watch(['development/index.html'],copyFn);
    next();
}
exports.watch = watchFn;


function fn1(next){
    console.log('a');
    next();
}

function fn2(next){
    console.log('b');
    next();
}

function fn3(next){
    console.log('c');
    next();
}

// 同步的批量执行
exports.syncAll = series(fn1,fn2,fn3);
// 异步的批量执行
exports.asyncAll = parallel(fn1,fn2,fn3);


function serverFn(next){
    connect.server({
        root:'dist',          //以哪个文件夹为服务器
        port:8888,            //端口号
        livereload:true,       //是否可以自动刷新
        middleware:function(){
            return [createProxyMiddleware("/api",{
                target: 'https://wanandroid.com/wxarticle',    //代理的目标地址
                changeOrigin:true,
                pathRewrite:{    //路径重写规则
                    '^/api':''
                }
            })]
        }
    })
    next();
}
exports.server = serverFn;

exports.serverWatch = parallel(serverFn,watchFn);



function hygFn(next){
    src(['development/js/*.js'])
    .pipe(concat('index.js'))
    .pipe(babel({
        presets: ['@babel/env']
    }))
    .pipe(dest("dist/js"))
    .pipe(uglify())
    .pipe(rename('index.min.js'))
    .pipe(dest('dist/js'))
    next();
}
exports.hyg = hygFn;


function sassTocssFn(){
    return src(['development/sass/loading.scss'])
    .pipe(sass().on('error',sass.logError))
    .pipe(dest('dist/css'))
}
exports.sTc = sassTocssFn;

function watchSassFn(next){
    watch(['development/sass/loading.scss'],sassTocssFn);
    next();
} 
exports.ws = watchSassFn;